package com.cykj.faceledtv.network;

import com.cykj.faceledtv.BuildConfig;
import com.cykj.faceledtv.MyApp;
import com.cykj.faceledtv.network.cookies.CookiesManager;
import com.cykj.faceledtv.network.download.DownLoadListener;
import com.cykj.faceledtv.network.download.DownloadInterceptor;
import com.cykj.faceledtv.utils.NetworkUtils;
import com.jakewharton.retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory;

import java.io.File;
import java.io.IOException;
import java.util.concurrent.TimeUnit;


import okhttp3.Cache;
import okhttp3.CacheControl;
import okhttp3.Interceptor;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.logging.HttpLoggingInterceptor;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;

/**
 * retrofit manager
 *
 * @author jzh
 * @date 2018/12/11 17:10
 */
public class RetrofitManager {
    private static final String CACHE_NAME = "retrofitCache";
    private static Retrofit retrofit = null;
    private static String url = "";

    private static volatile Retrofit downLoadRetrofit = null;

    public static Retrofit getInstance(String baseUrl) {
        url = baseUrl;
        if (retrofit == null) {
            return create();
        } else {
            return retrofit;
        }
    }

    /**
     * 获取下载文件的retrofit配置
     *
     * @param baseUrl baseUrl
     * @return retrofit
     */
    public static Retrofit getDownloadInstance(String baseUrl, DownLoadListener listener) {
        if (downLoadRetrofit == null) {
            synchronized (RetrofitManager.class) {
                if (downLoadRetrofit == null) {
                    return createDownload(baseUrl, listener);
                }
            }
        }
        return downLoadRetrofit;
    }

    private static Retrofit createDownload(String baseUrl, DownLoadListener listener) {
        OkHttpClient httpClient = new OkHttpClient.Builder()
                .addInterceptor(new DownloadInterceptor(listener))
                .retryOnConnectionFailure(true)
                .connectTimeout(10, TimeUnit.SECONDS)
                .build();

        downLoadRetrofit = new Retrofit.Builder()
                .baseUrl(baseUrl)
                .client(httpClient)
                .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                .build();
        return downLoadRetrofit;
    }


    private synchronized static Retrofit create() {
        OkHttpClient.Builder builder = new OkHttpClient.Builder();
        if (BuildConfig.DEBUG) {
            HttpLoggingInterceptor loggingInterceptor = new HttpLoggingInterceptor();
            loggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
            builder.addInterceptor(loggingInterceptor);
        }
        File cacheFile = new File(MyApp.getInstance().getExternalCacheDir(), CACHE_NAME);
        Cache cache = new Cache(cacheFile, 1024 * 1024 * 50);
        Interceptor cacheInterceptor = new Interceptor() {
            @Override
            public Response intercept(Chain chain) throws IOException {
                Request request = chain.request();
                if (!NetworkUtils.isNetworkConnected(MyApp.getInstance())) {
                    request = request.newBuilder()
                            .cacheControl(CacheControl.FORCE_CACHE)
                            .build();
                }
                Response response = chain.proceed(request);
                if (NetworkUtils.isNetworkConnected(MyApp.getInstance())) {
                    int maxAge = 0;
                    // 有网络时, 不缓存, 最大保存时长为0
                    response.newBuilder()
                            .header("Cache-Control", "public, max-age=" + maxAge)
                            .removeHeader("Pragma")
                            .build();
                } else {
                    // 无网络时，设置超时为4周
                    int maxStale = 60 * 60 * 24 * 28;
                    response.newBuilder()
                            .header("Cache-Control", "public, only-if-cached, max-stale=" + maxStale)
                            .removeHeader("Pragma")
                            .build();
                }
                return response;
            }
        };
        //设置缓存
        builder.addNetworkInterceptor(cacheInterceptor);
        builder.addInterceptor(cacheInterceptor);
        //token校验
//        builder.addInterceptor(new TokenInterceptor());
        builder.cache(cache);
        //是否使用cookies
        builder.cookieJar(new CookiesManager());
        //cookie认证
//        builder.cookieJar(new PersistentCookieJar(new SetCookieCache(),
//                new SharedPrefsCookiePersistor(MyApp.getInstance())));
        //设置超时
        builder.connectTimeout(10, TimeUnit.SECONDS);
        builder.readTimeout(20, TimeUnit.SECONDS);
        builder.writeTimeout(20, TimeUnit.SECONDS);
        //错误重连
        builder.retryOnConnectionFailure(true);
        retrofit = new Retrofit.Builder()
                .baseUrl(url)
                .addConverterFactory(GsonConverterFactory.create())
                .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                .client(builder.build())
                .build();
        return retrofit;
    }
}
